#include "doge_msgqueue.h"
#include "string.h"

static uint8_t is_queue_empty(stDgMsgQueueDef *mq)
{
    if(mq->in == mq->out)
    {
        return 1;
    }
    return 0;
}


static uint8_t is_queue_full(stDgMsgQueueDef *mq)
{
    if ( ( (mq->in+1) % DOGE_MSG_LEN) == mq->out)
    {
        return 1;
    }
	
    return 0;
}

enDgQueStateDef DG_MsgEnQueue(stDgMsgQueueDef *mq, uint8_t *buf, uint16_t buf_len)
{
    if ( is_queue_full (mq) == 1)  return DOGE_QUEUE_FULL;
    if (buf_len > DOGE_MSG_BUFFER_SIZE) return DOGE_QUEUE_EVAL;

    memcpy(&mq->msgs[mq->in], buf, buf_len);
    mq->in = (++mq->in) % DOGE_MSG_LEN;   
	return DOGE_QUEUE_OK;
}


/* 发送紧急消息 */
enDgQueStateDef DG_UrgentMsgEnQueue(stDgMsgQueueDef *mq, uint8_t *buf, uint16_t buf_len)
{
    if (IsMsgQueueFull(mq) == 1) return DOGE_QUEUE_FULL;
    if (buf_len > DOGE_MSG_BUFFER_SIZE) return DOGE_QUEUE_EVAL;

    if (mq->out == 0)
    {
        memcpy(&mq->msgs[DOGE_MSG_LEN - 1], buf, buf_len);
        mq->out = DOGE_MSG_LEN - 1;
    }
    else
    {
        mq->out = (--mq->out) % DOGE_MSG_LEN; //防止越界
        memcpy(&mq->msgs[mq->out], buf, buf_len);
    }
    return DOGE_QUEUE_OK;
}

enDgQueStateDef DG_MsgDequeue(stDgMsgQueueDef *mq, uint8_t *buf, uint16_t buf_len)
{
    if ( is_queue_empty(mq) ) return DOGE_QUEUE_EMPTY;
    if (buf_len > DOGE_MSG_BUFFER_SIZE) return DOGE_QUEUE_EVAL;

    memcpy(buf, &mq->msgs[mq->out], buf_len);
    mq->out = (++mq->out) % DOGE_MSG_LEN;   
    return DOGE_QUEUE_OK;
} 
